package cn.fayang.ymcc.listener;

import cn.fayang.ymcc.domain.CourseOrder;
import cn.fayang.ymcc.domain.PayOrder;
import cn.fayang.ymcc.dto.PayNotifyDto;
import cn.fayang.ymcc.service.IPayOrderService;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 事务消息监听器
 */
@Component
@RocketMQTransactionListener(
        txProducerGroup = "service-order-producer"  //要和发送事务消息指明的名字一致
)
public class CourseOrderRocketmqListener  implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;
    /**
     * 保存本地事务
     * @param message
     * @param
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        PayOrder payOrder = (PayOrder) arg;
        PayOrder orderTmp = payOrderService.selecByOrderNO(payOrder.getOrderNo());
        if(orderTmp.getPayStatus() != PayOrder.STATE_WAIT_PAY){//状态不对，不做修改
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        payOrderService.updateById(payOrder);
        return RocketMQLocalTransactionState.COMMIT;//执行本地事务成功
    }

    /**
     *查询本地事务
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bodyTmp = (byte[]) message.getPayload();
            String notifyDtoStr = new String(bodyTmp, StandardCharsets.UTF_8);
            PayNotifyDto dto = JSONObject.parseObject(notifyDtoStr, PayNotifyDto.class);
            if(dto != null){
                return RocketMQLocalTransactionState.UNKNOWN;//未知
            }
            PayOrder orderTmp = payOrderService.selecByOrderNO(dto.getOrderNo());
            if(orderTmp == null){
                return RocketMQLocalTransactionState.UNKNOWN;
            }
            //判断支付单的状态是否是已支付
            if(orderTmp.getPayStatus() == PayOrder.STATE_PAY_SUCCESS){
                return RocketMQLocalTransactionState.COMMIT;//才真正的发送事务消息成功
            }
            return RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
